<template>
  <div class="coupang">
    <el-row
      :gutter="10"
      style="
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: stretch;
      "
      class="clearfix"
    >
      <!--      <el-col :span="0">-->
      <!--        <LeftTree-->
      <!--          :treelist="treeList"-->
      <!--          :search_data.sync="searchData"-->
      <!--          fieldname="shop_id"-->
      <!--          @refesh_list="getItemList"-->
      <!--          style="height: 100%"-->
      <!--        ></LeftTree>-->
      <!--      </el-col>-->
      <el-col :span="24" style="height: auto">
        <div v-if="search_visible" id="search" class="search">
          <el-form ref="form" :model="searchData">
            <el-row :gutter="10">
              <el-col :span="5">
                <el-form-item style="line-height: 0">
                  <treeselect
                    style="display: inline-block"
                    :append-to-body="true"
                    :default-expand-level="1"
                    v-model="searchData.shop_id"
                    :options="shop_ids"
                    :normalizer="normalizer"
                    :show-count="true"
                    placeholder="请选择所属店铺"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item>
                  <el-input
                    id="company_name"
                    v-model="searchData.product_title"
                    placeholder="请输入商品名称"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="5">
                <el-form-item>
                  <el-input
                    v-model="searchData.sellerProductId"
                    placeholder="请输入商品SKU"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item>
                  <search-tool
                    :search_data.sync="searchData"
                    @refesh_list="getItemList"
                  ></search-tool>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <!-- 工具栏 -->
        <div class="sku_header_left">
          <!--          @click="refreshList"-->
          <!--          -->
          <div>
            <el-button
              type="primary"
              size="small"
              class="el-icon-refresh"
              @click="syncSKU"
              :loading="load && percentage !== 100"
            >
              同步SKU
            </el-button>
          </div>

          <el-progress
            v-if="load && percentage !== 100"
            :text-inside="true"
            style="width: 50%"
            :percentage="percentage"
            :stroke-width="26"
            :format="format"
            text-color="#fff"
          ></el-progress>
          <div>
            <TableTool
              :search_visible.sync="search_visible"
              @refesh_list="getItemList"
            ></TableTool>
          </div>
        </div>
        <!-- 数据列表 -->
        <el-table
          :height="
            search_visible
              ? $store.state.user.clientHeight - 280
              : $store.state.user.clientHeight - 240
          "
          @expand-change="expandChange"
          :data="tableData"
          style="width: 100%"
          :header-cell-style="{
            border: '1px solid #eee',
            background: '#f5f7fa',
            color: '#14142B',
            height: '28px',
            padding: '5px 0',
          }"
          v-loading="loading"
          ref="multipleTable"
          @cell-click="cellClick"
          :cell-style="{ padding: '8px,0' }"
        >
          <template slot="empty">
            <img
              class="empty-img"
              src="@/assets/imgs/zanwushuju.svg"
              style="width: 64px; height: 50px"
              alt=""
            />
            <div class="noCart">暂无数据</div>
          </template>
          <el-table-column align="right" width="1" type="expand">
            <template slot-scope="props">
              <!-- <h2 class="skuCalss" style="">SKU列表</h2> -->
              <el-table
                class="childTable"
                :data="props.row.childrenData"
                v-loading="props.row.loading"
                border
                :header-cell-style="{
                  border: '1px solid #eee',
                  background: '#f5f7fa',
                  color: '#14142B',
                  height: '28px',
                  padding: '5px 0',
                  fontSize: '13px',
                }"
                style="width: 100%"
                :key="props.row.keyId"
                :row-style="{ height: '0' }"
                :cell-style="{ padding: '5px', fontSize: '12px' }"
              >
                <el-table-column
                  prop="sku_No"
                  align="center"
                  show-overflow-tooltip
                  label="SKU"
                >
                </el-table-column>
                <el-table-column
                  prop="product_title.zh"
                  align="center"
                  show-overflow-tooltip
                  label="中文品名"
                >
                </el-table-column>
                <el-table-column
                  prop="univalent"
                  show-overflow-tooltip
                  label="单价(USD)"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  prop="hs_code"
                  align="center"
                  show-overflow-tooltip
                  label="HSCODE"
                >
                </el-table-column>
                <el-table-column
                  align="center"
                  property="amount"
                  label="数量"
                  show-overflow-tooltip
                >
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column align="center" type="selection" width="60">
          </el-table-column>
          <el-table-column
            align="center"
            property="images"
            label="平台商品图片"
            width="250px"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <div class="demo-image__preview">
                <el-image
                  v-show="index < 1"
                  v-for="(item, index) in scope.row.images"
                  :key="'abc' + index"
                  @click="preView(scope.row.images)"
                  style="width: 100px; height: 100px; margin-left: 5px"
                  :src="`${imgUrl}${item.cdnPath}`"
                  :preview-src-list="srcList"
                >
                </el-image>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="" width="280" label="平台商品信息" prop="">
            <template slot-scope="scope">
              <div v-if="scope.row.sellerProductId" class="labels">
                <span>商品编号：</span>{{ scope.row.sellerProductId }}
              </div>
              <div v-if="scope.row.sellerProductItemId" class="labels">
                <span>商品SKU：</span>{{ scope.row.sellerProductItemId }}
              </div>
              <div v-if="scope.row.vendorItemId" class="labels">
                <span>店铺商品ID：</span>{{ scope.row.vendorItemId }}
              </div>
              <div v-if="scope.row.product" class="labels_blue">
                <span>商品原始名：</span
                >{{ scope.row.product.sellerProductName }}
              </div>
              <div v-if="scope.row.itemName" class="labels">
                <span>商品类型名：</span>{{ scope.row.itemName }}
              </div>
              <div
                v-if="scope.row.salePrice"
                class="labels"
                style="color: #0cc50c"
              >
                <span
                  >售卖价格：<i style="font-weight: bold; color: #0cc50c"
                    >₩&nbsp;</i
                  ></span
                >{{ scope.row.salePrice }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="" width="260" label="商品信息" prop="">
            <template slot-scope="scope">
              <div v-if="scope.row.sku_item_No" class="labels">
                <span>SKU组号：</span>{{ scope.row.sku_item_No }}
              </div>
              <div v-if="scope.row.product_title" class="labels">
                <span>申报中文名：</span>{{ scope.row.product_title.zh }}
              </div>
              <div v-if="scope.row.product_title" class="labels">
                <span>申报英文名：</span>{{ scope.row.product_title.en }}
              </div>
              <div v-if="scope.row.univalent" class="labels">
                <span>总申报价格：</span>{{ scope.row.univalent }}&nbsp;<span
                  style="font-weight: bold; color: #0cc50c"
                  >USD</span
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column align="" width="200" label="商品属性">
            <template slot-scope="scope">
              <div>
                <el-checkbox
                  v-model="scope.row.specifications.charged"
                  class="checkbtn labels"
                  ><span class="labels">是否带电?</span>
                </el-checkbox>
              </div>
              <div>
                <el-checkbox
                  v-model="scope.row.specifications.liquid"
                  class="checkbtn labels"
                  ><span class="labels">是否液体?</span>
                </el-checkbox>
              </div>
              <div v-if="scope.row.weight" class="labels">
                <span>总申报重量：</span>{{ scope.row.weight }}&nbsp;<span
                  style="font-weight: bold; color: #0cc50c"
                  >KG</span
                >
              </div>
              <div v-if="scope.row.volume" class="labels">
                <span>总申报尺寸：</span>{{ scope.row.volume.L }}CM*{{
                  scope.row.volume.W
                }}CM*{{ scope.row.volume.H }}CM
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" width="200" prop="" label="展开SKU">
            <template slot-scope="scope">
              <span class="labels" style="color: #24acf2; cursor: pointer"
                >展开SKU<i class="el-icon-d-caret"></i
              ></span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            property="product.saleStartedAt"
            label="创建时间"
            width="160px"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <div class="operate">
                <el-button
                  @click="linkSkuClick(scope.row)"
                  type="text"
                  size="small"
                  ><i class="el-icon-edit"></i>&nbsp;关联SKU
                </el-button>
                <el-button type="text" size="small"
                  ><i class="el-icon-edit"></i>&nbsp;操作日志
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <Pagination :child-msg="pageparm" @callFather="callFather"></Pagination>
      </el-col>
    </el-row>

    <!-- Sku模态框 -->
    <CoupangModal
      @submit="submitClick"
      @closeForm="closeDialog"
      :dialogVisible.sync="dialogVisible"
      :editData="editData"
      :dialogTitle="dialogTitle"
    ></CoupangModal>
    <edit-modal
      @submit1="submitClick1"
      @closeForm="closeDialog1"
      :dialogVisible1.sync="dialogVisible1"
      :editData1="editData1"
      :dialogTitle1="dialogTitle1"
    ></edit-modal>
  </div>
</template>

<script>
import {
  getShopList,
  getItemList,
  refreshSKU,
  addSkuItem,
  updateSku,
  getItemUpdateInfo,
  itemUpdateInfo,
  getUpdateInfo,
  addSku,
  chooseSku,
} from "@/api/coupang";
import Treeselect from "@riophae/vue-treeselect";
import "element-ui/lib/theme-chalk/display.css";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import CoupangModal from "@/views/warehouse/components/CoupangModal.vue";
import editModal from "@/views/warehouse/components/editModal.vue";
//引入websocket
import { getClientId } from "@/utils/auth";
import store from "@/store";

export default {
  components: {
    editModal,
    Treeselect,
    CoupangModal,
  },
  data() {
    return {
      dialogVisible1: false,
      editData1: {},
      dialogTitle1: "",
      //---------------------------------------
      searchData: {
        sellerProductId: "",
      },
      search_visible: true,
      //---------------------------------------
      loading: false,
      load: false,
      formInline: {
        page: 1,
        limit: 20,
      },
      treeList: [],
      shop_ids: [],
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 20,
        total: 0,
      },
      tableData: [],
      dialogVisible: false,
      dialogTitle: "",
      editData: {},
      imgUrl: "",
      srcList: [],
      percentage: 0,
      total: 0,
      // ws: void 0,// ws链接
      client_id: "",
    };
  },
  created() {
    if (this.$route.query.id) {
      this.searchData.sellerProductId = this.$route.query.id;
      this.getItemList();
    } else {
      this.getShopList();
      this.getItemList();
    }
  },
  destroyed() {},
  watch: {
    "$store.state.order.status": {
      deep: true, //深度监听设置为 true
      handler: function (newVal, oldVal) {
        if (newVal === 200) {
          this.$message({
            type: "success",
            message: store.state.order.notice_content,
          });
        } else if (newVal === 411) {
          this.$message({
            type: "error",
            message: store.state.order.notice_content,
          });
        }
      },
    },
    "$store.state.order.Num": {
      deep: true, //深度监听设置为 true
      handler: function (newVal, oldVal) {
        this.percentage = newVal;
      },
    },
  },
  methods: {
    cellClick(row, column, event) {
      if (event.cellIndex === 6) {
        this.$refs.multipleTable.toggleRowExpansion(row);
      }
    },
    submitClick(val) {
      if (val.sku_item_No) {
        this.addSkuItem(val);
      } else if (val.hs_code) {
        this.addSku(val);
      } else {
        this.updateSku(val);
      }
    },
    //关联SKU中，新建Sku保存
    async addSku(val) {
      const res = await addSku(val);
      if (res.data.status === 200) {
        this.getItemList();
        this.$message({
          type: "success",
          message: res.data.msg,
        });
      } else {
        this.$message({
          type: "error",
          message: res.data.msg,
        });
      }
    },
    async submitClick1(val) {
      const res = await itemUpdateInfo(val);
      if (res.data.status === 200) {
        this.getItemList();
        this.$message({
          type: "success",
          message: res.data.msg,
        });
      } else {
        this.$message({
          type: "error",
          message: res.data.msg,
        });
      }
    },
    preView(row) {
      this.srcList = [];
      row.forEach((item) => {
        this.srcList.push(`${this.imgUrl}${item.cdnPath}`);
      });
    },
    //修改全部SKU
    async editClick(row) {
      const res = await getItemUpdateInfo({
        product_sku_item_id: row.product_sku_item_id,
      });
      if (res.data.status === 200) {
        this.dialogVisible1 = true;
        this.dialogTitle1 = "修改全部";
        this.editData1 = res.data.data;
      } else {
        this.$message({
          type: "error",
          message: res.data.msg,
        });
      }
    },
    //获取店铺列表
    async getShopList() {
      this.loading = true;
      try {
        const res = await getShopList();
        if (res.data.status === 200) {
          this.treeList = res.data.data;
          this.shop_ids = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
        this.loading = false;
      } catch (error) {
        this.loading = false;
        this.$message.error("系统错误");
      }
    },
    //获取店铺信息
    async getItemList() {
      console.log(this.searchData.shop_id);
      this.loading = true;
      try {
        let obj = {};
        Object.assign(obj, this.searchData, this.formInline);
        const res = await getItemList(obj);
        if (res.data.status === 200) {
          this.tableData = res.data.data.data.map((item, index) => {
            item.keyId = item.product_sku_item_id;
            item.childrenData = []; // 添加子表格数据
            return item;
          });
          this.imgUrl = res.data.imgUrl;
          this.pageparm.currentPage = res.data.data.current_page;
          this.pageparm.total = res.data.data.total;
          this.pageparm.pageSize = res.data.data.per_page;
        } else {
          this.$message.error(res.data.msg);
        }
        this.loading = false;
      } catch (error) {
        this.loading = false;
        this.$message.error("系统错误");
      }
    },
    //获取sku列表
    async chooseSku(row) {
      // 通过$set属性可设置loading实现实时加载loading效果(经过测试,通过$set直接给父层数据声明子层数据时会出现报错,所以才在获取父层表格数据时声明子层表格数据)
      this.$set(row, "loading", true);
      try {
        const res = await chooseSku({
          product_sku_item_id: row.product_sku_item_id,
        });
        if (res.data.status === 200) {
          // 遍历父层表格数据
          this.tableData.forEach((temp, index) => {
            // 找到当前展开的行，把获取到的数据赋值进去
            if (temp.keyId === row.product_sku_item_id) {
              this.$set(this.tableData[index], "childrenData", res.data.data);
            }
          });
          this.$set(row, "loading", false);
        } else {
          this.$set(row, "loading", false);
        }
      } catch (error) {
        this.$set(row, "loading", false);
        this.$message.error("系统错误");
      }
    },
    expandChange(row, expandedRows) {
      this.chooseSku(row);
    },
    //------------------------------弹窗、分页器----------------------------------
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
    },
    closeDialog1() {
      this.dialogVisible1 = false;
    },
    //分页插件
    callFather(parm) {
      this.formInline.page = parm.currentPage;
      this.formInline.limit = parm.pageSize;
      this.getItemList(this.formInline);
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.val,
        label: node.key,
        children: node.children,
      };
    },
    //关联SKU
    linkSkuClick(row) {
      this.editData = row;
      this.dialogTitle = "关联SKU";
      this.dialogVisible = true;
    },
    //提交SKU组
    async addSkuItem(obj) {
      const res = await addSkuItem(obj);
      if (res.data.status === 200) {
        this.getItemList();
        this.$message({
          type: "success",
          message: res.data.msg,
        });
      } else {
        this.$message({
          type: "error",
          message: res.data.msg,
        });
      }
    },
    async updateSku(obj) {
      const res = await updateSku(obj);
      if (res.data.status === 200) {
        this.getItemList();
        this.$message({
          type: "success",
          message: res.data.msg,
        });
      } else {
        this.$message({
          type: "error",
          message: res.data.msg,
        });
      }
    },
    //---------------------同步SKU--------------------------
    async syncSKU() {
      if (this.searchData.shop_id) {
        this.percentage = 0;
        this.total = 0;
        this.load = true;
        // 执行脚本
        const res = await refreshSKU({
          shop_id: this.searchData.shop_id,
          client_id: getClientId().client_id,
        });
        if (res.data.status === 200) {
          this.$message.success(res.data.msg);
        } else {
          this.$message.error(res.data.msg);
        }
      } else {
        this.$message.warning("请先选择店铺");
      }
    },
    // socket接受提示信息
    getSock(msg) {
      if (msg.data !== "服务器连接成功！") {
        let data = "";
        try {
          data = JSON.parse(msg.data);
          if (data.status === 411) {
            this.load = false;
            this.$message.warning(data.msg);
          }
          if (typeof data.msg == "number") {
            this.percentage = data.msg;
            this.total = data.total;
            if (data.msg === 100) return this.$message.success("同步完成");
          }
        } catch (e) {
          return false;
        }
      }
    },
    format(percentage) {
      return `${percentage}%:${this.total}条`;
    },
    //请求接口
    // async refreshSKU(obj) {
    //   console.log('进度条')
    //   const res = await refreshSKU(obj);
    //   if (res.data.status === 200) {
    //     this.$message.success(res.data.msg);
    //   } else {
    //     Bus.$off("message");
    //     this.$message.error(res.data.msg);
    //   }
    // },
  },
};
</script>
<style lang="scss" scoped>
.el-table {
  border: 1px solid #eee;
  border-top: none;
  border-bottom: none;
}

::v-deep .el-table__expand-icon {
  visibility: hidden !important;
}

::v-deep .demo-table-expand {
  font-size: 0;
}

::v-deep .form_div .demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

::v-deep .el-progress-bar__inner {
  text-align: left;
}

.form_div {
  display: flex;
  justify-content: space-around;
  align-items: center;
  background-color: #f5f7fa;

  .el-form-item {
    display: flex;
    align-items: center;
  }
}

//.demo-table-expand .el-form-item[data-v-b2cbea06] {
//  margin-right: 0;
//  margin-bottom: 0;
//  width: 100%;
//  display: flex;
//  align-items: center;
//}

.el-progress {
  line-height: 3;
}

.operate {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.el-button + .el-button {
  margin-left: 0;
}

::v-deep .vue-treeselect__control {
  height: 34px;
}

::v-deep .el-form-item__content {
  line-height: 0;
}

.checkbtn {
  ::v-deep .el-checkbox__inner {
    border-radius: 50%;
  }
}

.beyond {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 150px;
}

.el-form-item {
  margin-bottom: 0;
}

::v-deep .el-form-item__label {
  text-align: center;
}

::v-deep .el-input__inner {
  height: 32px;
  line-height: 32px;
}

.coupang {
  padding: 5px 10px;
}

.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.labels {
  font-size: 12px;

  span {
    font-size: 12px;
    color: #a9a9a9;
    font-weight: 400;
  }

  &:hover {
    color: #000;
  }
}

.labels_blue {
  font-size: 13px;
  color: #2e82ff;

  span {
    color: #a9a9a9;
  }

  &:hover {
    cursor: pointer;
  }
}

.childTable {
  padding: 10px 10px;
}

.skuCalss {
  text-align: center;
  line-height: 52px;
  background-color: skyblue;
  color: #fff;
  font-weight: 400;
}

.el-icon-download {
  margin: 0 8px;
}

.sku_header_left {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
}

//清除浮动
.clearfix:before,
.clearfix:after {
  display: table;
  content: ""; /*不用有内容也可以*/
}

.clearfix:after {
  clear: both;
}

.clearfix {
  *zoom: 1;
}
</style>
